import Koa from 'koa'
import Router from 'koa-router'
import json from 'koa-json'
import bodyParser from 'koa-bodyparser'
import cors from '@koa/cors'
import fs from 'fs'
import {fileURLToPath} from "url"
import path from "path"
import koa_static from 'koa-static'
import koa_ejs from '@koa/ejs'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const app = new Koa()

app.use(cors())
app.use(koa_static(__dirname + '/public', { maxAge: 7 * 24 * 60 * 60 * 1000 }))
app.use(bodyParser({ enableTypes: ['json', 'form', 'text'] }))
app.use(json())
koa_ejs(app, { root: 'view', layout:false, cache: true })

const router = new Router()

router.get('/editor/:key', async (ctx) => {
  const key = ctx.params.key.toLowerCase()
  const config = JSON.parse(fs.readFileSync(`./config/${key}.json`, 'utf-8'))
  await ctx.render('lowcode', { key, config, menu: { key } })
})

router.get('/', async (ctx) => {
  const key = 'index'
  const config = JSON.parse(fs.readFileSync(`./config/${key}.json`, 'utf-8'))
  await ctx.render('preview', { key, config, menu: { key } })
})

router.get('/:key', async (ctx) => {
  const key = ctx.params.key.toLowerCase()
  const config = JSON.parse(fs.readFileSync(`./config/${key}.json`, 'utf-8'))
  await ctx.render('preview', { key, config, menu: { key } })
})

router.get('/api/menu/preview/:key', async (ctx) => {
  const key = ctx.params.key.toLowerCase()
  const config = JSON.parse(fs.readFileSync(`./config/${key}.json`, 'utf-8'))
  await ctx.render('preview', { key, config, menu: { key } })
})

router.post('/api/menu/editor/:key', async (ctx) => {
  const key = ctx.params.key.toLowerCase()
  if (!fs.existsSync('./config')) { fs.mkdirSync('./config') }
  fs.writeFileSync(`./config/${key}.json`, JSON.stringify(ctx.request.body, null, 2))
  ctx.body = {}
})

app.use(router.routes())
app.use(router.allowedMethods())

process.on("uncaughtException", function (err) { console.error(err, "Uncaught exception") })
process.on("unhandledRejection", (reason, promise) => { console.error({ promise, reason }, "Unhandled Rejection at: Promise") })

// 启动服务器
app.listen(3000, () => {
  console.log(`Server is running at http://localhost:3000`)
})
